package com.bsb.biz.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.bsb.base.common.util.StringUtils;
import com.bsb.base.model.SysOrganization;
import com.bsb.base.model.SysUser;
import com.bsb.biz.service.SysOrganizationService;
import com.bsb.biz.service.SysUserService;
import com.bsb.biz.spring.SpringUtils;

public class UserUtils {
	private static SysUserService sysUserService;
	private static SysOrganizationService sysOrganizationService;
	
	public static SysUserService getSysUserService(){
		if(null == sysUserService){
			sysUserService = SpringUtils.getBean(SysUserService.class);
		}
		return sysUserService;
	}
	
	public static SysOrganizationService getSysOrganizationService(){
		if(null == sysOrganizationService){
			sysOrganizationService = SpringUtils.getBean(SysOrganizationService.class);
		}
		return sysOrganizationService;
	}
	
	public static SysUser currentUser(){
		Subject subject = SecurityUtils.getSubject();
		String username = (String)subject.getPrincipal();
		if (StringUtils.isNotEmpty(username)){
			SysUser user = getSysUserService().getUserByUsername(username);
			if (user != null){
				Long organization_id = user.getOrganization_id();
				SysOrganization sysOrganizationById = getSysOrganizationService().getSysOrganizationById(organization_id);
				Long firmId = sysOrganizationById.getFirmId();
				if(null != sysOrganizationById && null != firmId){
					user.setFirmId(firmId);
				}
				return user;
			}
			return new SysUser();
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new SysUser();
	}
}
